package com.baidu.foodrecipe.ui.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.baidu.foodrecipe.data.local.entity.FavoriteEntity
import com.baidu.foodrecipe.databinding.RecipeItemBinding
import com.baidu.foodrecipe.ui.bindingEvents.ClickEvents


class FavoriteAdapter : RecyclerView.Adapter<FavoriteAdapter.MyViewHolder>() {
    private var itemList = emptyList<FavoriteEntity>()

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): MyViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = RecipeItemBinding.inflate(inflater)
        return MyViewHolder(binding)
    }

    override fun onBindViewHolder(
        holder: MyViewHolder,
        position: Int
    ) {
        holder.bind(itemList[position])
    }

    //获取item的数量 + 加载更多的item
    override fun getItemCount(): Int {
        return itemList.size
    }

    class MyViewHolder(val binding: RecipeItemBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(favorite: FavoriteEntity) {

            binding.itemModel = favorite.result
            binding.events = ClickEvents()
            binding.isFavoritePage = true
            binding.executePendingBindings()
        }
    }

    fun setNewData(newItems: List<FavoriteEntity>) {
        //使用DiffUtil去分析新旧数据是否相同
        //通过CallBack抽象类来告诉DiffUtil我是如何判断相同和不相同的规则的
        val diffResult = DiffUtil.calculateDiff(DiffCallBackImpl(itemList, newItems))
        //修改数据源
        itemList = newItems
        //使用diffUtil去刷新Adapter
        diffResult.dispatchUpdatesTo(this)
    }

    private class DiffCallBackImpl(
        val itemList: List<FavoriteEntity>,
        val newItems: List<FavoriteEntity>
    ) : DiffUtil.Callback() {

        override fun getOldListSize(): Int {
            return itemList.size
        }

        override fun getNewListSize(): Int {
            return newItems.size
        }

        override fun areItemsTheSame(
            oldItemPosition: Int,
            newItemPosition: Int
        ): Boolean {
            //比较两个对象是否相同
            //java中使用 == 来判断两个对象是否相同
            //kotlin中使用 ===
            return itemList[oldItemPosition].result.id == newItems[newItemPosition].result.id
        }

        override fun areContentsTheSame(
            oldItemPosition: Int,
            newItemPosition: Int
        ): Boolean {
            //比较两个对象的内容是否相同
            //java中使用 equals 来判断两个对象的内容是否相同
            //kotlin中使用 ==
            return itemList[oldItemPosition].result == newItems[newItemPosition].result
        }
    }
}
